//
//  LandingViewController.m
//  HZHome
//
//  Created by SunShine on 13-9-19.
//  Copyright (c) 2013年 xzysun. All rights reserved.
//

#import "LandingViewController.h"
#import "IconPagesViewController.h"
#import "ChooseStreetViewController.h"
#import "PersonalCenterViewController.h"
#import "MyConCernViewController.h"
#import "StreetInfoService.h"
#import "MyStreetViewController.h"
#import "MySupervisionViewController.h"
#import "WorkQueryViewController.h"
#import "MessageService.h"
#import "ParticipationAwardViewController.h"
#import "JSBadgeView.h"
#import "ParticipateService.h"
#import "RegisterViewController.h"
#import "AwardViewController.h"
#import "ListViewController.h"
#import "InfoViewController.h"
#import "CommunityFunctionViewController.h"
#import "CommunityUserRelation.h"
#import "MapNearListViewController.h"

@interface LandingViewController () <ParticipateServiceDelegate,UITableViewDataSource,UITableViewDelegate,UITextFieldDelegate>
@property (strong, nonatomic) MBProgressHUD *loadingView;
@property (strong, nonatomic) StreetInfoService *streetInfoService;
@property (strong, nonatomic) JSBadgeView *msgBadgeView;
@property (strong, nonatomic) IBOutlet UIButton *personalCenterButton;
@property (strong, nonatomic) IBOutlet UIButton *messageButton;

@property (nonatomic) BOOL isCallingParticipationAward;
@property (strong, nonatomic) NSMutableArray *datas;
-(void)autoLogin;
@end

@implementation LandingViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    //读取配置文件
    
    self.datas = [[NSMutableArray alloc] init];
    
    NSString *plistPath = [[NSBundle mainBundle] pathForResource:@"IconPages" ofType:@"plist"];
    _iconPageConfigs = [[NSDictionary alloc]initWithContentsOfFile:plistPath];
    self.navigationController.navigationBarHidden = YES;
    //注册刷新首页显示的街道的通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(refreshStreetName) name:REFRESH_USER_STREET_ID_NOTIFICATION_NAME object:nil];
    
    
    
    //执行自动登录
    [self autoLogin];
    if (RunTimeOSVersion >= 7.0) {
//        NSString *constraintStr = @"V:[_titleImage(==60)]";
//        NSMutableArray *tmpConstraints = [NSMutableArray array];
//        [tmpConstraints addObjectsFromArray:[NSLayoutConstraint constraintsWithVisualFormat:constraintStr options:NSLayoutFormatDirectionLeadingToTrailing metrics:nil views:NSDictionaryOfVariableBindings(_titleImage)]];
//        [self.view addConstraints:tmpConstraints];
        CGRect titleFrame = self.titleImage.frame;
        titleFrame.size.height = 64.0;
        self.titleImage.frame = titleFrame;
        CGRect titleLabelFrame = self.titleLabel.frame;
        titleLabelFrame.origin.y += 20.0;
        self.titleLabel.frame = titleLabelFrame;
        CGRect titleButtonFrame = self.streetButton.frame;
        titleButtonFrame.origin.y += 20.0;
        self.streetButton.frame = titleButtonFrame;
        CGRect scrollFrame = self.scrollView.frame;
        scrollFrame.origin.y += 20.0;
        scrollFrame.size.height -= 20.0;
        self.scrollView.frame = scrollFrame;
    } else {
//        NSString *constraintStr = @"V:[_titleImage(==40)]";
//        NSMutableArray *tmpConstraints = [NSMutableArray array];
//        [tmpConstraints addObjectsFromArray:[NSLayoutConstraint constraintsWithVisualFormat:constraintStr options:NSLayoutFormatDirectionLeadingToTrailing metrics:nil views:NSDictionaryOfVariableBindings(_titleImage)]];
//        [self.view addConstraints:tmpConstraints];
//        CGRect titleFrame = self.titleImage.frame;
//        titleFrame.size.height = 44.0;
//        self.titleImage.frame = titleFrame;
    }
    self.scrollView.contentSize = CGSizeMake(SCREEN_WIDTH, 504.0);
    //在个人中心的按钮上增加一个数字
    self.msgBadgeView = [[JSBadgeView alloc]initWithParentView:self.messageButton alignment:JSBadgeViewAlignmentTopRight];
    self.msgBadgeView.badgePositionAdjustment = CGPointMake(0, -5);
//    [self.view addSubview:self.msgBadgeView];
    
    [self.navigationController setNavigationBarHidden:YES animated:YES];
    
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 300, 320, 150)];
//    [self.tableView setFrame:CGRectMake(0, 300, 320, 90)];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.scrollEnabled = NO;
    [self.scrollView addSubview:self.tableView];
    [self getList];
}

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
//    self.navigationController.navigationBarHidden = YES;
    [self.navigationController setNavigationBarHidden:YES animated:YES];
    [self.tabBarController.tabBar setHidden:NO];
    self.searchTextField.delegate = self;
    if (RunTimeOSVersion >= 7.0) {
        [self.searchView setFrame:CGRectMake(0, 20, 320, 45)];
    }
    
    //刷新街道列表
    _streetInfoService = [StreetInfoService getService];
    [_streetInfoService getStreetListFromServer];
   
    //选择街道按钮
    NSString *storedName = [DataStoreService loadFromDefaults:CURRENT_SELECTED_STREET_NAME_KEY];
    NSLog(@"viewWillAppear  streetName=%@",storedName);
    if (storedName && storedName.length > 0) {
        [self.streetButton setTitle:storedName forState:UIControlStateNormal];
    } else {
        [self.streetButton setTitle:@"定制街道" forState:UIControlStateNormal];
    }
    //读取消息数量
    [[MessageService new] loadMessageCount:^(NSString *count) {
        self.msgBadgeView.badgeText = count;
        
    }];
    [self.tableView setFrame:CGRectMake(0, 301, 320, 150)];
    self.searchTextField.text = @"";
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Refresh Street
-(void)refreshStreetName
{
    NSString *name = _streetInfoService.selectedStreetName;
    NSLog(@"刷新首页的街道名称为%@",name);
    if (name == nil || name == (id)[NSNull null] || name.length == 0) {
        name = @"定制街道";
    }
    [_streetButton setTitle:name forState:UIControlStateNormal];
}


- (void)getList
{
    NSMutableDictionary *params = [NSMutableDictionary dictionary];

    MKNetworkEngine *currentEngine = [[MKNetworkEngine alloc] initWithHostName:GetList customHeaderFields:nil];
    MKNetworkOperation *op = [currentEngine operationWithPath:@"" params:params httpMethod:@"POST"];
    [op addCompletionHandler:^(MKNetworkOperation *completedOperation) {
        
//        NSDictionary *json = [completedOperation responseJSON];
        [self.datas removeAllObjects];
        NSArray *array = [completedOperation responseJSON];
        [self.datas addObjectsFromArray:array];
        [self.tableView reloadData];
        
    } errorHandler:^(MKNetworkOperation *completedOperation, NSError *error) {
        
    }];
    [currentEngine enqueueOperation:op];
}

#pragma mark - Button Actions
//设置街道
- (IBAction)changeStreetAction:(id)sender
{
    ChooseStreetViewController *chooseVC = [[ChooseStreetViewController alloc]initWithNibName:@"ChooseStreetViewController" bundle:nil];
    [self.navigationController  pushViewController:chooseVC animated:YES];
}

//我的关注
- (IBAction)myConcernAction:(id)sender
{
    MyConCernViewController *concernVC = [[MyConCernViewController alloc]initWithNibName:@"MyConCernViewController" bundle:nil];
    concernVC.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:concernVC animated:YES];
}

//我要监督
- (IBAction)mySuperviseAction:(id)sender
{
    self.isCallingParticipationAward = YES;
    
    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"http://www.haizhu.gov.cn/app/"]];

    return;
    if (![UserInfoService getUserInfoService].currentLoginUserName) {
        UIAlertView * alertview = [[UIAlertView alloc]initWithTitle:@"提示" message:@"该功能注册用户才能使用。现在注册" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
        
        [alertview show];
        return;
    }
    [ParticipateService share].delegate = self;
    [[ParticipateService share] isParticipate];
}

- (void)isParticipate:(BOOL)isSuccess
{
    // 改为始终进入这个页面
    ParticipationAwardViewController *vc = [[ParticipationAwardViewController alloc]init];
    vc.hasJoined = isSuccess;
    vc.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:vc animated:YES];
}

//我要查
- (IBAction)myInquiryAction:(id)sender
{
    [self showIconPagesWithName:@"我要查"];
}

//办事及指南查询
- (IBAction)queryGuideAction:(id)sender
{
//    [self showIconPagesWithName:@"办事及指南查询"];
    WorkQueryViewController *vc = [[WorkQueryViewController alloc]initWithNibName:@"WorkQueryViewController" bundle:nil];
    vc.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:vc animated:YES];
}

//我的街道
- (IBAction)myStreetAction:(id)sender
{
    if (![StreetInfoService getService].selectedStreetId) {
        UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"提示" message:@"请先定制我的街道" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
        [alert show];
        return;
    }
    MyStreetViewController *iconPageVC = [[MyStreetViewController alloc]initWithNibName:@"MyStreetViewController" bundle:nil];
    iconPageVC.config = [_iconPageConfigs objectForKey:@"我的街道"];
    iconPageVC.hidesBottomBarWhenPushed = YES;

    [self.navigationController pushViewController:iconPageVC animated:YES];
}

//居民服务
- (IBAction)residentServiceAction:(id)sender
{
    [self showIconPagesWithName:@"居民服务"];
}

//企业服务
- (IBAction)enterpriseServiceAction:(id)sender
{
    [self showIconPagesWithName:@"企业服务"];
}

//文化旅游
- (IBAction)culturalTourismAction:(id)sender
{
    [self showIconPagesWithName:@"文化旅游"];
}

//志愿者服务
- (IBAction)volunteerAction:(id)sender
{
    [self showIconPagesWithName:@"志愿者服务"];
}

//个人中心
- (IBAction)personalCenterAction:(id)sender
{
    PersonalCenterViewController *pcVC = [[PersonalCenterViewController alloc]initWithNibName:@"PersonalCenterViewController" bundle:nil];
    pcVC.isBottomNavigationGoIn = 1;
    [self.navigationController pushViewController:pcVC animated:YES];
}

//社区自治
- (IBAction)societyManage:(id)sender
{
//    UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:nil message:@"正在建设中" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
//    [alertView show];
    //验证是否注册
    [self isRegistCommunity];

}

-(void)showIconPagesWithName:(NSString*)name
{
    IconPagesViewController *iconPageVC = [[IconPagesViewController alloc]initWithNibName:@"IconPagesViewController" bundle:nil];
    iconPageVC.config = [_iconPageConfigs objectForKey:name];
    iconPageVC.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:iconPageVC animated:YES];
}

- (IBAction)mapRoute:(id)sender
{
    MapNearListViewController *vc = [[MapNearListViewController alloc] initWithNibName:@"MapNearListViewController" bundle:nil];
    vc.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:vc animated:YES];

}

#pragma mark tableView
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 30.0f;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.datas.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *cellIdentifier = @"cellIdentifier";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    if (!cell) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:cellIdentifier];
        
        UILabel *textLabel = [[UILabel alloc] initWithFrame:CGRectMake(26, 0, 300, 30)];
        [textLabel setBackgroundColor:[UIColor clearColor]];
        textLabel.tag = 1000;
        [textLabel setFont:[UIFont systemFontOfSize:12.0f]];
        [cell.contentView addSubview:textLabel];
        
        UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(5 , 7, 16, 16)];
        imageView.image = [UIImage imageNamed:@"btjt.png"];
        [cell.contentView addSubview:imageView];
    }
    NSDictionary *dict = self.datas[indexPath.row];
    UILabel *textLabel = (UILabel *)[cell.contentView viewWithTag:1000];
    textLabel.text = dict[@"name"];
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSDictionary *dict = self.datas[indexPath.row];
    
    NSString *dataType = dict[@"dataType"];
    InfoViewController *vc = [[InfoViewController alloc] init];
    vc.serverId = [dict[@"id"] stringValue];
    vc.url = [dataType isEqualToString:@"NOTICE"] ? InfoWithNotice : InfoWithScene;
    vc.hidesBottomBarWhenPushed = YES;
    [self.navigationController setNavigationBarHidden:NO];
    [self.navigationController pushViewController:vc animated:YES];
}

#pragma mark - Alert Delegate
-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    BOOL tempselfIsCallingParticipationAward = self.isCallingParticipationAward;
    self.isCallingParticipationAward = NO;
    if (buttonIndex == 0) {
        return;
    } else if (tempselfIsCallingParticipationAward) {
        RegisterViewController *registerVC = [[RegisterViewController alloc]initWithNibName:@"RegisterViewController" bundle:nil];
        [self.navigationController pushViewController:registerVC animated:YES];
    } else {
        [self changeStreetAction:nil];
    }
}

#pragma mark - Auto Login
-(void)autoLogin
{
    [UserInfoService getUserInfoService].delegate = self;
//    NSString *userName = [DataStoreService loadFromKeychain:AUTO_LOGIN_USER_NAME];
//    NSString *userPass = [DataStoreService loadFromKeychain:AUTO_LOGIN_USER_PASSWORD];
//    if (userName && userPass) {
//        NSLog(@"检测到保存的用户名密码,准备自动登录.");
//        //显示一个覆盖全屏的读取框
//        UIWindow *aWindow = [[UIApplication sharedApplication].windows objectAtIndex:0];
//        self.loadingView = [[MBProgressHUD alloc]initWithWindow:aWindow];
//        _loadingView.labelText = @"正在自动登录...";
//        [aWindow addSubview:_loadingView];
//        [_loadingView show:YES];
//        //执行自动登录
//        [[UserInfoService getUserInfoService] checkUserLoginWithName:userName andPassword:userPass];
//    }
    if (isStart == 1) {
        return;
    }
    isStart=0;//初始化为未登录的状态
    UIWindow *aWindow = [[UIApplication sharedApplication].windows objectAtIndex:0];
        self.loadingView = [[MBProgressHUD alloc]initWithWindow:aWindow];
        _loadingView.labelText = @"正在自动登录...";
        [aWindow addSubview:_loadingView];
        [_loadingView show:YES];
    [[UserInfoService getUserInfoService] autoLogin];
}

-(void)loadUserInfoFinished:(id)result
{
    NSLog(@"自动登录成功");
    //保存用户信息
    [[UserInfoService getUserInfoService] loginSuccessHandler:result];
    //读取登录后的街道信息
    [_loadingView removeFromSuperview];
    [_loadingView hide:YES];
    [[NSNotificationCenter defaultCenter]postNotificationName:@"successLoginWithIndexViewController" object:nil];
}

-(void)loadUserInfoFaild:(NSString *)msg
{
    NSLog(@"自动登录失败");
    [_loadingView removeFromSuperview];
    [_loadingView hide:YES];
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [textField resignFirstResponder];
    
    if ([textField.text length] > 0) {
        
        
        MapNearListViewController *vc = [[MapNearListViewController alloc] initWithNibName:@"MapNearListViewController" bundle:nil];
        vc.classStr = textField.text;
        vc.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:vc animated:YES];

        
////        ListViewController *vc = [[ListViewController alloc]initWithNibName:@"ListViewController" bundle:nil];
////        vc.searchText = textField.text;
////        vc.hidesBottomBarWhenPushed = YES;
////        NSMutableDictionary *vcConfig = [[NSMutableDictionary alloc] init];
////        [vcConfig setObject:textField.text forKey:@"key"];
////        [vcConfig setObject:[NSNumber numberWithBool:YES] forKey:@"MyConcern"];
////        [vcConfig setObject:textField.text forKey: @"fastSearchKey"];
////        [vcConfig setObject:@"MyConcernService" forKey:@"myGudieServe"];
////        [vcConfig setObject: @"InfoWithPhoneAndMapCell" forKey:@"myGudieCell"];
////        
////        vc.config = vcConfig;
//        self.navigationController.navigationBarHidden = NO;
//        [self.navigationController pushViewController:vc animated:YES];
    }

    
    return YES;
}

- (IBAction)searchKeyText:(id)sender
{
    [self.searchTextField resignFirstResponder];

    if ([self.searchTextField.text length]) {
        ListViewController *vc = [[ListViewController alloc]initWithNibName:@"ListViewController" bundle:nil];
        vc.searchText = self.searchTextField.text;
        vc.hidesBottomBarWhenPushed = YES;
        NSMutableDictionary *vcConfig = [[NSMutableDictionary alloc] init];
        [vcConfig setObject:self.searchTextField.text forKey:@"key"];
        [vcConfig setObject:[NSNumber numberWithBool:YES] forKey:@"MyConcern"];
        [vcConfig setObject:self.searchTextField.text forKey: @"fastSearchKey"];
        [vcConfig setObject:@"MyConcernService" forKey:@"myGudieServe"];
        [vcConfig setObject: @"InfoWithPhoneAndMapCell" forKey:@"myGudieCell"];
        
        vc.config = vcConfig;
        self.navigationController.navigationBarHidden = NO;
        [self.navigationController pushViewController:vc animated:YES];

    }
}


//查看用户是否以注册社区用户
- (void)isRegistCommunity
{
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    UserInfoService *userInfo=[UserInfoService getUserInfoService];
    if ([params objectForKey:@"userId"]==nil) {
        [params setValue:userInfo.userInfo.Id forKey:@"userId"];
        NSLog(@"userId = %@",userInfo.userInfo.Id);
    }
    MKNetworkEngine *currentEngine = [[MKNetworkEngine alloc] initWithHostName:SERVER_URL_COMMUNITY_IS_REGISTER customHeaderFields:nil];
    MKNetworkOperation *op = [currentEngine operationWithPath:@"" params:params httpMethod:@"POST"];
    [op addCompletionHandler:^(MKNetworkOperation *completedOperation) {
        NSDictionary *json = [completedOperation responseJSON];
        BOOL isRegist = [[json objectForKey:@"isRegister"] boolValue];
        if (isRegist) {//
            int state = [[json objectForKey:@"state"]intValue];
            if (state == 1) {//0：正在审核。1：审核通过。2：审核不通过 ,
                NSDictionary *bean = [json objectForKey:@"communityUserRelation"];
                //字典转实体
               CommunityUserRelation *cur = getObjectFromDic([CommunityUserRelation class],bean);
                IconPagesViewController *iconPageVC = [[IconPagesViewController alloc]initWithNibName:@"IconPagesViewController" bundle:nil];

                NSMutableDictionary *mConfig =[NSMutableDictionary dictionaryWithDictionary:[_iconPageConfigs objectForKey:@"社区自治"]];
                 
                [mConfig setValue:cur.communityName forKeyPath:@"title"];
                
                [mConfig setValue:@"社区自治" forKeyPath:@"keyTitle"];
                [mConfig setValue:[NSString stringWithFormat:@"%@",[CommonUtil dealNullObject:cur.streetId]] forKeyPath:@"streetId"];
                [mConfig setValue:[NSString stringWithFormat:@"%@", [CommonUtil dealNullObject:cur.communityId]] forKeyPath:@"communityId"];
                [mConfig setValue:[NSString stringWithFormat:@"%@",[CommonUtil dealNullObject:cur.communityName]] forKeyPath:@"communityName"];
                [mConfig setValue:[NSString stringWithFormat:@"%@",[CommonUtil dealNullObject:cur.partyMember]] forKeyPath:@"partyMember"];
                [mConfig setObject:[CommonUtil dealNullObject:cur.streetId] forKey:@"streetId"];
                [mConfig setObject:[CommonUtil dealNullObject:cur.streetName] forKey:@"streetName"];
                [mConfig setObject:[CommonUtil dealNullObject:cur.waiterId] forKey:@"waiterId"];
                iconPageVC.config =mConfig;
                iconPageVC.hidesBottomBarWhenPushed = YES;
                [self.navigationController pushViewController:iconPageVC animated:YES];
            }else{
                CommunityFunctionViewController *pcVC =[[CommunityFunctionViewController alloc]initWithNibName:@"CommunityFunctionViewController" bundle:nil];
                pcVC.hidesBottomBarWhenPushed = YES;//隐藏底部导航
                [self.navigationController pushViewController:pcVC animated:YES];
                
            }
            
        }else{//如果没有注册,跳到 “社区注册参加页”
            CommunityFunctionViewController *pcVC =[[CommunityFunctionViewController alloc]initWithNibName:@"CommunityFunctionViewController" bundle:nil];
            pcVC.hidesBottomBarWhenPushed = YES;//隐藏底部导航
            [self.navigationController pushViewController:pcVC animated:YES];
        }
        
        
    } errorHandler:^(MKNetworkOperation *completedOperation, NSError *error) {
        
    }];
    [currentEngine enqueueOperation:op];
}
@end
